﻿using System;
using Com.Fubei.OpenApi.Sdk.Enums;
using Com.Fubei.OpenApi.Sdk.Exceptions;
using Com.Fubei.OpenApi.Sdk.Models;
using Com.Fubei.OpenApi.Sdk.Utils;
using Com.Fubei.OpenApi.Sdk.Extensions;

namespace Com.Fubei.OpenApi.Sdk
{
    public static class FubeiOpenApiSdk
    {
        private static T PostRequest<T>(string url, FubeiBizParam param)
        {
            var requestParam = param.GenerateAsFubeiRequestParam();
            var json = HttpUtil.PostRequest(url, requestParam);
            return json.DeserializeFromJson<T>();
        }

        /// <summary>
        /// 回调签名验证
        /// </summary>
        /// <param name="result"></param>
        /// <param name="sign"></param>
        /// <param name="apiLevel"></param>
        /// <returns></returns>
        public static bool VerifyFubeiNotification(FubeiApiCommonResult<string> result, string sign, EApiLevel apiLevel)
        {
            var secret = apiLevel == EApiLevel.Merchant
                ? FubeiOpenApiGlobalConfig.Instance.AppSecret
                : FubeiOpenApiGlobalConfig.Instance.VendorSecret;
            
            return FubeiSignatureUtil.Verify(result, secret, sign);
        }

        /// <summary>
        /// 获得Api地址
        /// </summary>
        /// <param name="openApiVer">接口版本号 1: 开放平台1.0  2: 开放平台2.0</param>
        private static string GetApiUrlByVersion(int openApiVer = 2)
        {
            return openApiVer == 1 ? 
                FubeiOpenApiGlobalConfig.Instance.Api_1_0 : FubeiOpenApiGlobalConfig.Instance.Api_2_0;
        }

        [Obsolete("使用开放平台2.0接口")]
        public static FubeiApiCommonResult<T> PostMerchantApiRequest<T>(string method, object param) where T : new()
        {
            return PostRequest<FubeiApiCommonResult<T>>(GetApiUrlByVersion(1), param.WithFubeiBizParam(method, EApiLevel.Merchant));
        }

        /// <summary>
        /// 2.0接口 - 同步
        /// </summary>
        /// <param name="method">方法名</param>
        /// <param name="param">请求实体</param>
        /// <param name="apiLevel">接口级别: EApiLevel.Merchant：商户级 Vendor：服务商级 </param>
        /// <typeparam name="T">返回实体</typeparam>
        /// <returns></returns>
        public static T PostApiRequest<T>(string method, object param, EApiLevel apiLevel = EApiLevel.Merchant) where T : new()
        {
            var result = PostRequest<FubeiApiCommonResult<T>>(GetApiUrlByVersion(2), param.WithFubeiBizParam(method, apiLevel));
            if (result.ResultCode != 200)
            {
                throw new BizException(result.ResultCode, result.ResultMessage);
            }

            return result.Data;
        }
    }
}
